﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.Authorization;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata;
using OfficeOpenXml;
using SubstrateHelper.Data;
using SubstrateHelper.Models;
using System.IO;


namespace SubstrateHelper.Pages
{
    public class PageDownloadSchedulingFileModel : PageModel
    {
        
        SubstrateHelper.Data.SubstrateHelperDbContext Db;

        public string Message { get; set; }
        public PageDownloadSchedulingFileModel(SubstrateHelperDbContext db)
        {
            Db = db;
        }

        public async Task<IActionResult> OnGetAsync(string SchedulingLotNo)
        {
            ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
            if (true)//if (User.IsInRole("数据库管理员"))
            {                
                try
                {
                    string file = Path.Combine(Directory.GetCurrentDirectory(), $"GeneratedFile\\{SchedulingLotNo}.xlsx");
                    ExcelPackage xlPackage = new ExcelPackage(new FileInfo(file));
                    
                    byte[] bt = xlPackage.GetAsByteArray();
                    System.IO.File.Delete(file);                    
                    FileContentResult result = new FileContentResult(bt, "application/octet-stream");

                    result.FileDownloadName = Path.GetFileName(file);
                    return result;
                }
                catch(Exception ex)
                {
                    Message = ex.Message;
                    return Page();
                }                

            }
            else
            {
                Message = "您没有下载权限！您目前登录的账号没有包含“数据库管理员”角色！";
                return Page();
            }
        }
        
    }
}